package com.ys.nms.module.business.controller.admin.storage;

import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.io.IOException;

import com.ys.nms.framework.common.pojo.PageParam;
import com.ys.nms.framework.common.pojo.PageResult;
import com.ys.nms.framework.common.pojo.CommonResult;
import com.ys.nms.framework.common.util.object.BeanUtils;

import static com.ys.nms.framework.common.pojo.CommonResult.success;

import com.ys.nms.framework.excel.core.util.ExcelUtils;

import com.ys.nms.framework.apilog.core.annotation.ApiAccessLog;

import static com.ys.nms.framework.apilog.core.enums.OperateTypeEnum.*;

import com.ys.nms.module.business.controller.admin.storage.vo.*;
import com.ys.nms.module.business.dal.dataobject.storage.StorageDO;
import com.ys.nms.module.business.service.storage.StorageService;

@Tag(name = "管理后台 - 存储表")
@RestController
@RequestMapping("/business/storage")
@Validated
public class StorageController {

    @Resource
    private StorageService storageService;

    @PostMapping("/create")
    @Operation(summary = "创建存储表")
    @PreAuthorize("@ss.hasPermission('business:storage:create')")
    public CommonResult<Integer> createStorage(@Valid @RequestBody StorageSaveReqVO createReqVO) {
        return success(storageService.createStorage(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新存储表")
    @PreAuthorize("@ss.hasPermission('business:storage:update')")
    public CommonResult<Boolean> updateStorage(@Valid @RequestBody StorageSaveReqVO updateReqVO) {
        storageService.updateStorage(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除存储表")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('business:storage:delete')")
    public CommonResult<Boolean> deleteStorage(@RequestParam("id") Integer id) {
        storageService.deleteStorage(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除存储表")
    @PreAuthorize("@ss.hasPermission('business:storage:delete')")
    public CommonResult<Boolean> deleteStorageList(@RequestParam("ids") List<Integer> ids) {
        storageService.deleteStorageListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得存储表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('business:storage:query')")
    public CommonResult<StorageRespVO> getStorage(@RequestParam("id") Integer id) {
        StorageDO storage = storageService.getStorage(id);
        return success(BeanUtils.toBean(storage, StorageRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得存储表分页")
    public CommonResult<PageResult<StorageRespVO>> getStoragePage(@Valid StoragePageReqVO pageReqVO) {
        PageResult<StorageDO> pageResult = storageService.getStoragePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, StorageRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得存储表分页")
    public CommonResult<List<StorageRespVO>> getStorageList(@Valid StoragePageReqVO pageReqVO) {
        List<StorageDO> list = storageService.getStorageListByDeviceId(pageReqVO.getDeviceId());
        List<StorageRespVO> voList = BeanUtils.toBean(list, StorageRespVO.class);


// 假设 list 是 List<StorageRespVO>
        for (StorageRespVO storage : voList) {
            Long size = storage.getStorageSize();
            Long used = storage.getStorageUsed();
            Long free = storage.getStorageFree();
            Integer units = storage.getStorageUnits();

            // 防空判断
            if (size == null || used == null || free == null || units == null) {
                System.out.println("存储数据不完整: " + storage);
                continue;
            }

            // 转换为字节
            long totalBytes = size * units;
            long usedBytes = used * units;
            long freeBytes = free * units;

            // 转换为 GB，保留两位小数
            storage.setTotalGb(bytesToGb(totalBytes));
            storage.setUsedGb(bytesToGb(usedBytes));
            storage.setFreeGb(bytesToGb(freeBytes));

            // 计算精确使用率（百分比）
            BigDecimal usageRate = BigDecimal.valueOf(usedBytes * 100.0 / totalBytes)
                    .setScale(2, RoundingMode.HALF_UP);
            storage.setUsageRate(usageRate);

            // 可选：打印验证
            System.out.printf("设备ID: %d, 描述: %s, 总容量: %.2f GB, 使用率: %s%%%n",
                    storage.getDeviceId(), storage.getStorageDescr(),
                    storage.getTotalGb(), storage.getUsageRate());
        }

        return success(voList);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出存储表 Excel")
    @PreAuthorize("@ss.hasPermission('business:storage:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportStorageExcel(@Valid StoragePageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<StorageDO> list = storageService.getStoragePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "存储表.xls", "数据", StorageRespVO.class,
                BeanUtils.toBean(list, StorageRespVO.class));
    }


    private BigDecimal bytesToGb(long bytes) {
        return BigDecimal.valueOf(bytes)
                .divide(BigDecimal.valueOf(1024 * 1024 * 1024), 2, RoundingMode.HALF_UP);
    }


}